newsletter = function(){

    var ajaxUrl = AdMin.base_url +"/modules/newsletter/admin/ajax.php";
    var ucfirst = function (str) { str += ''; return str.charAt(0).toUpperCase() + str.substr(1); }
    var renderActive = function (val) { return '<span class="ico_'+ val +'"></span>'; }

    var renderEdit = function(value, p, record) { 
        return String.format('<b><a href="javascript: AdMin.clientes.openItem({0}, \'details.php?clienteID={0}\', \'{1}\') ">{2}</a></b>',record.data.clienteID, record.data.nombre_apellido, value); 
    }

    var deleteUser = function (btn) {
        if(btn=='yes') {
            var slctn = usersGrid.getSelectionModel().getSelections();
            for(var i = 0, record, arPIDs = Array(); record = slctn[i]; i++) {
                arPIDs.push(record.data.clienteID);
            }
            Ext.Ajax.request({
               url: ajaxUrl +'?c=clientes&action=delete',
               success: function() {
                   usersStore.reload();
                   Ext.AdMin.msg(AdMin.lang.translate("status"),AdMin.lang.translate("status"))
				},
				failure: function() {
					Ext.Msg.show({
						title: AdMin.lang.translate("error_delete_record"),
                        msg: res.message,
						icon: Ext.MessageBox.ERROR
					});
				},
				params: { 'clienteID[]': arPIDs }
            });
        }
    };

    /*
    * USERS STORE
    */
    var usersStore = new Ext.data.JsonStore({
        root: 'users',
        totalProperty: 'totalCount',
        idProperty: 'id',
        autoDestroy: true,
        remoteSort: true,
        fields: [{name:'id', type: 'int'},'email', 'date_created'],
        url: ajaxUrl +'?c=newsletter&action=newsletter_list'
    });
    usersStore.setDefaultSort('id', 'asc');
    usersStore.load({params:{start:0, limit: AdMin.newsletter.numMaxListedRows}});

    /*
    * GRID
    */
    var colModel = new Ext.grid.ColumnModel({
        defaults: { sortable: true },
        columns: [
            {header: "id", width: 45, dataIndex: 'id'},
            {id:'email', header: AdMin.lang.translate('email'), width: 120, dataIndex: 'email'},
            {header: AdMin.lang.translate('date_created'), width: 110, dataIndex: 'date_created'}
        ]
    });
    
    var usersGrid = new Ext.grid.GridPanel({
        flex : 1,
        border : false,
        store: usersStore,
        columnLines: true,
        stripeRows: true,
        autoExpandColumn: 'email',
        loadMask: true,
        // Columns and CheckboxSelectionModel plugin
        cm: colModel,
        selModel : new Ext.grid.RowSelectionModel({singleSelect:true}),
        // paging bar on the bottom
        bbar: new Ext.PagingToolbar({
            pageSize: AdMin.newsletter.numMaxListedRows,
            store: usersStore,
            displayInfo: true,
            displayMsg: AdMin.lang.translate('displayin_n-m_of_p'),
            emptyMsg: AdMin.lang.translate('no_records_found'),
            buttons:[
                '-','&nbsp;',
                {   // Export: 
                    iconCls: 'silk-export',
                    text: AdMin.lang.translate('Export CSV'),
                    handler: function(){
                        document.location.href = AdMin.base_url+'/modules/newsletter/admin/export.php?export=1&query='+Ext.getCmp('newsletter-search-field').getValue();
                    }
                }
            ]
        })
    });

    usersGrid.getSelectionModel().on('selectionchange', function(sm) {
//        usersPanel.removeBtn.setDisabled(sm.getCount() < 1);
    });

    var usersPanel = new Ext.Panel({
        region : "center",
        layout : "vbox",
        border : true,
        margins: '5 5 5 5',
        layoutConfig: {
            align : 'stretch',
            pack  : 'start'
        },
        split : true,
        // task bar
        tbar: [/*{
        iconCls: 'silk-add',
            text: AdMin.lang.translate("add"),
            handler: function() {
                AdMin.clientes.openItem('', "abm.php",'Creando usuario');
            }
        },
        '-',
        {
            ref: '../removeBtn',
            iconCls: 'silk-delete',
            text: AdMin.lang.translate("delete"),
            disabled: true,
            handler: function() {
                Ext.MessageBox.confirm(AdMin.lang.translate('warning'),  AdMin.lang.translate('are_you_sure_to_delete'), deleteUser);
            },
            tooltip: AdMin.lang.translate("click_here_to_delete_selected")
        },
        '-',*/
        AdMin.lang.translate('search'),
        new Ext.app.SearchField({
            id : "newsletter-search-field",
            store: usersStore,
            width:290
        })
        ],
        bodyStyle : "background-color:  #E5EDF8;",
        items : [ usersGrid ]
    });


    AdMin.newsletter.tabs = new Ext.TabPanel({
        region : "center",
        activeTab:0,
        flex:1,
        resizeTabs:true, // turn on tab resizing
        minTabWidth: 115,
        border: true,
        tabWidth:180,
        id : "newsletter-module",
        enableTabScrole:true,
        defaults: {autoScrole:false},
        listeners : {
            "tabchange": function(main, tab) {
                if(tab.onTabChange)  tab.onTabChange(tab);
            }
        },
        plugins: new Ext.ux.TabCloseMenu(),
        items : [{
            xtype: "panel",
            border: false,
            layout: "border",
            title: ucfirst(AdMin.lang.translate('Newsletter')),
            items : usersPanel
        }]
    });

    AdMin.newsletter.openItem = function(id, url, name){
        titleTab = (id == '' ? name : "clienteID: "+id+" - "+name);
        AdMin.newsletter.tabs.add({
            title: titleTab,
            html: '<iframe src="'+ AdMin.base_url +"modules/clientes/admin/"+ url +'" style="width: 100%; height:100%; border: none" frameborder="0"></iframe>',
            closable:true
        }).show();
    }

    return AdMin.newsletter.tabs;
};
